<?php


namespace Admin\Controller;


use Common\Controller\BaseController;
use Common\Model\CategoryModel;
use Common\Model\TypeModel;
use Org\Util\Base;

class CategoryController extends BaseController
{

    public function index(){

        $data=m('category')->select();
        $data=(new Base())->tree($data,'cname','cid','pid');
        $this->assign('data',$data);


        $this->display();
    }

    public function add(){
        $field=m('type')->select();
        $this->assign('field',$field);
        if (IS_POST){
//            dd($_POST);die;
            $data=I('post.');
            $this->store(new CategoryModel(),$data,u('admin/category/index'));

        }





        $this->display();

    }
    public function set(){
        $cid=I('get.cid');
        if (IS_POST){
            $data=I('post.');
            $this->store(new CategoryModel(),$data,u('admin/category/index'));

        }
        $data=m('category')->find($cid);
        $this->assign('data',$data);

        $field=m('type')->select();
        $this->assign('field',$field);
//        dd($field);


        $this->display();
    }


    public function edit(){
        $cid=I('get.cid');
        $oldData=m('category')->find($cid);
//        dd($oldData);
        $this->assign('oldData',$oldData);



       $field =(new CategoryModel())->getCateData($cid);
        $this->assign('field',$field);
//        dd($field);

            $type=m('type')->select();
            $this->assign('type',$type);
//            dd($type);



        if (IS_POST){
            $data=I('post.');
            if ($cid){
                $data['cid']=$cid;
            }
            $this->store(new CategoryModel(),$data, u('admin/Category/index',['cid'=>$_GET['cid']]));
        }




//        $User = D("type")->find(1);
//        $user = $User->relation(true)->find(1);
//        dd($User);


        $this->display();
    }


    public function del(){

        $cid=I('get.cid');

        $ss=m('category')->select();
        $pid = M('category')->where("cid={$cid}")->getField('pid');
//        dd($pid);die;
        foreach ($ss as $k=>$v ){
           if ($cid==$v['pid']) {
              M('category')->pid=$pid;
               M('category')->where("pid={$cid}")->save();

           }
        }

//        dd($ss);die;

        (new CategoryModel())->where("cid={$cid}")->delete();
        $this->success('操作成功',u('admin/Category/index'));
    }

}